<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Search</title>
</head>
<body>
	<h1>Search assistant</h1>
	<hr/>
	<form> 
		Input：<input type="text" id="txt1" name="q"/>
	</form>
	<div id="hint" style="margin-left:55px" ></div>
	<script type="text/javascript">
	// 使用闭包，通过operator返回的obj调用obj内的function
		var text=document.getElementById("txt1");
		text.addEventListener("keyup",function(){
			var op=operator(text,text.value);
			op.sendText(); //闭包调用
		});

		function operator(text,value){
			var obj={};
			obj.sendText=function(){
				document.getElementById("hint").innerHTML="";
				var xhr=new XMLHttpRequest();
				if (value.length==0){
  					return;
  				}
				xhr.open("GET","http://localhost:9090/Homework_W5Tues/query?q="+value,true);
				xhr.send();
				xhr.onreadystatechange=function(){
  					if (xhr.readyState==4 && xhr.status==200){
  						var response=JSON.parse(xhr.responseText);
  						response.forEach((item)=>{
  							var p=document.createElement("p");
  							var text = document.createTextNode(item);
  							p.appendChild(text);
  							document.getElementById("hint").appendChild(p);
  						});   			
    				}
  				}
			};
			return obj;
		}
	</script>
</body>
</html>